document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    // 显示用户名
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('username').textContent = user.username;
    }

    // 获取URL参数中的游戏ID
    const urlParams = new URLSearchParams(window.location.search);
    const gameId = urlParams.get('id');

    // 获取游戏详情
    async function fetchGameDetails() {
        try {
            const response = await fetch(`http://localhost:3000/api/games/${gameId}`);
            const game = await response.json();
            renderGameDetails(game);
        } catch (error) {
            console.error('获取游戏详情失败:', error);
        }
    }

    // 渲染游戏详情
    function renderGameDetails(game) {
        const gameDetail = document.getElementById('gameDetail');
        gameDetail.innerHTML = `
            <div class="game-header">
                <img src="${game.image_url}" alt="${game.title}" class="game-cover">
            </div>
            <div class="game-info">
                <h1 class="game-title">${game.title}</h1>
                <div class="game-meta">
                    <div class="game-price">¥${game.price}</div>
                    <div class="game-rating">★ ${game.rating}</div>
                </div>
                <div class="game-tags">
                    ${game.tags.map(tag => `<span class="game-tag">${tag}</span>`).join('')}
                </div>
                <p class="game-description">${game.description}</p>
                <div class="game-details">
                    <div class="detail-item">
                        <div class="detail-label">开发商</div>
                        <div>${game.developer}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">发行商</div>
                        <div>${game.publisher}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">发行日期</div>
                        <div>${game.release_date || '暂无'}</div>
                    </div>
                </div>
            </div>
        `;
    }

    // 初始化评分系统
    const stars = document.querySelectorAll('.stars i');
    let currentRating = 0;

    stars.forEach(star => {
        star.addEventListener('mouseover', function() {
            const rating = this.dataset.rating;
            updateStars(rating);
        });

        star.addEventListener('click', function() {
            currentRating = this.dataset.rating;
        });
    });

    document.querySelector('.stars').addEventListener('mouseleave', () => {
        updateStars(currentRating);
    });

    function updateStars(rating) {
        stars.forEach(star => {
            const starRating = star.dataset.rating;
            star.className = starRating <= rating ? 'fas fa-star' : 'far fa-star';
        });
    }

    // 提交评价
    document.getElementById('submitReview').addEventListener('click', async () => {
        const reviewText = document.getElementById('reviewText').value;
        if (!reviewText || !currentRating) {
            alert('请填写评价内容并选择评分');
            return;
        }

        try {
            const response = await fetch(`http://localhost:3000/api/games/${gameId}/reviews`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    content: reviewText,
                    rating: currentRating
                })
            });

            if (response.ok) {
                alert('评价提交成功！');
                document.getElementById('reviewText').value = '';
                currentRating = 0;
                updateStars(0);
                fetchReviews();
            }
        } catch (error) {
            console.error('提交评价失败:', error);
            alert('提交评价失败，请稍后重试');
        }
    });

    // 获取评价列表
    async function fetchReviews() {
        try {
            const response = await fetch(`http://localhost:3000/api/games/${gameId}/reviews`);
            const reviews = await response.json();
            renderReviews(reviews);
        } catch (error) {
            console.error('获取评价失败:', error);
        }
    }

    // 渲染评价列表
    function renderReviews(reviews) {
        const reviewList = document.getElementById('reviewList');
        reviewList.innerHTML = reviews.map(review => `
            <div class="review-item">
                <div class="review-header">
                    <div class="review-user">${review.username}</div>
                    <div class="review-rating">★ ${review.rating}</div>
                </div>
                <div class="review-content">${review.content}</div>
            </div>
        `).join('');
    }

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', () => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'login.html';
    });

    // 初始化页面
    fetchGameDetails();
    fetchReviews();
}); 